import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../utils/G.dart';
import '../../utils/widgets/my_sliver_delegate.dart';

import '../../utils/order_types.dart';

class OrderList extends StatefulWidget {
  int type = 1;
  OrderList({Key? key, required int this.type}) : super(key: key);

  @override
  _OrderListState createState() => _OrderListState();
}

class _OrderListState extends State<OrderList> {
  List types = getOrderTypes();
  int currentIndex = 1;
  List list = [];
  int page = 1;

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _onRefresh();
  }

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 400));

    var res = await G.api.order.list(
      type: widget.type,
      page: 1,
    );
    if (res['status'] == 200) {
      list = res['data'];
    }
    if (mounted) {
      setState(() {});
    }

    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    page++;
    // monitor network fetch
    await Future.delayed(const Duration(milliseconds: 400));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    var res = await G.api.order.list(
      type: widget.type,
      page: 1,
    );
    if (res['status'] == 200) {
      list.addAll(res['data']);
    }

    if (mounted) {
      setState(() {});
    }

    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('订单列表'),
        centerTitle: true,
      ),
      body: _renderFreshList(),
    );
  }

  Widget _renderFreshList() {
    return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const WaterDropHeader(),
        footer: const ClassicFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          slivers: [
            // 具有吸顶效果的导航菜单
            SliverPersistentHeader(
                pinned: true, // 吸顶
                floating: false, // 反向滚动时，内容是否立即变大
                delegate: MySliverDelegate(
                    minHeight: 50,
                    maxHeight: 50,
                    child: Container(
                        height: 50,
                        child: ListView.builder(
                            itemCount: types.length,
                            scrollDirection: Axis.horizontal,
                            itemBuilder: (cxt, index) {
                              return _renderType(index);
                            })))),
            SliverPadding(
                padding: const EdgeInsets.all(1.0),
                sliver: MyOrderList(list: list)),
          ],
        ));
  }

  Widget _renderType(int i) {
    return GestureDetector(
        child: Container(
            width: G.width / types.length,
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 10),
            decoration: BoxDecoration(
                color: currentIndex == i
                    ? Colors.blue.shade100
                    : Colors.grey.shade100,
                border: Border(
                    bottom: BorderSide(
                  width: 3,
                  color: currentIndex == i
                      ? Colors.blue.shade200
                      : Colors.grey.shade100,
                ))),
            child: Text(types[i]['title'],
                style: TextStyle(
                    color: currentIndex == i
                        ? Theme.of(context).primaryColor
                        : Colors.black45,
                    fontWeight:
                        currentIndex == i ? FontWeight.w600 : FontWeight.w400,
                    fontSize: 16))),
        onTap: () {
          currentIndex = i;
          widget.type = types[i]['key'];

          // 重新发送请求
          _onRefresh();
        });
  }
}

class MyOrderList extends StatefulWidget {
  List list;
  MyOrderList({Key? key, required List this.list}) : super(key: key);

  @override
  _MyOrderListState createState() => _MyOrderListState();
}

class _MyOrderListState extends State<MyOrderList> {
  @override
  Widget build(BuildContext context) {
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      // 获取单个订单信息
      var item = widget.list[index];
      return Container(
        padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
        color: Colors.grey.shade200,
        child: Container(
          padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
          color: Colors.white,
          child: Column(
            children: [
              _orderHeader(item),
              _orderBody(item),
              _orderFooter(item)
            ],
          ),
        ),
      );
    }, childCount: widget.list.length));
  }

  Widget _orderHeader(Map item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(item['_add_time']),
        Text(item['_status']['_title'],
            style: const TextStyle(color: Colors.blue))
      ],
    );
  }

  Widget _orderBody(Map item) {
    return Wrap(
      spacing: 10,
      direction: Axis.horizontal,
      alignment: WrapAlignment.start,
      children: List<Widget>.generate(item['cartInfo'].length, (int index) {
        return Container(
          child: ListTile(
            isThreeLine: true,
            onTap: () {
              Map<String, dynamic> p = {
                'id': item['cartInfo'][index]['product_id']
              };
              G.router.navigateTo(
                  context, '/product_detail' + G.parseQuery(params: p));
            },
            leading: G.imageWidget(
                item['cartInfo'][index]['productInfo']['image'],
                width: 100,
                height: 100),
            title: Text(
              item['cartInfo'][index]['productInfo']['store_name'].toString(),
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: Column(
              children: [
                Row(
                  children: [
                    Text(
                      item['cartInfo'][index]['productInfo']['attrInfo']['sku'],
                      style: const TextStyle(
                        fontSize: 16,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.left,
                    )
                  ],
                ),
                Row(
                  children: [
                    Text(
                        "￥ " + item['cartInfo'][index]['truePrice'].toString()),
                    Text(
                        " X " + item['cartInfo'][index]['cart_num'].toString()),
                  ],
                ),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _orderFooter(Map item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        RichText(
            text: TextSpan(
                text: "总金额：",
                style: TextStyle(fontSize: 20, color: Colors.grey.shade700),
                children: [
              TextSpan(
                text: "￥ " + item['total_price'].toString(),
                style: TextStyle(
                    fontSize: 20,
                    color: Theme.of(context).primaryColor,
                    fontWeight: FontWeight.w600),
              )
            ])),
        ElevatedButton(
            onPressed: () {
              Future.delayed(const Duration(milliseconds: 400), () {
                Map<String, String> p = {"uni": item['order_id'].toString()};
                G.router.navigateTo(
                    context, '/order_detail' + G.parseQuery(params: p));
              });
            },
            child: const Text('查看详情'))
      ],
    );
  }
}
